package com.ruoyi.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.mapper.ElongMapper;
import com.ruoyi.service.ElongService;
import com.ruoyi.utils.ElongUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class ElongServiceImpl implements ElongService {

    @Autowired
    ElongMapper elongMapper;

    @Override
    public String getLoginToken() {
        Map map = elongMapper.getLoginToken();
        if (map == null) {
            // 生成accessToken
            String overdueTimeStr = DateUtils.getOverdueTime(1);
            String loginToken = ElongUtils.login();
            elongMapper.insertLoginToken(loginToken, overdueTimeStr);
            return loginToken;
        } else {
            String overdueTimeStr = map.get("overdue_time").toString();
            String loginToken = map.get("login_token").toString();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime overdueTimeDate = LocalDateTime.parse(overdueTimeStr);
            if (now.isBefore(overdueTimeDate)) {
                return loginToken;
            } else {
                overdueTimeStr = DateUtils.getOverdueTime(1);
                loginToken = ElongUtils.login();
                elongMapper.updateLoginToken(loginToken, overdueTimeStr);
                return loginToken;
            }
        }
    }
}
